<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  orderRefundExport,
  orderRefundList,
} from '#/api/business/order-refund';

import { columns, querySchema } from './data';

const formOptions: VbenFormProps = {
  commonConfig: {
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
  },
  fieldMappingTime: [
    [
      'createTime',
      ['startDate', 'endDate'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
  schema: querySchema(),
  showCollapseButton: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
};

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  id: 'order-refund-index',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        return await orderRefundList({
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
  rowConfig: {
    keyField: 'orderId',
  },
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

/**
 * 导出数据
 */
const openExportModal = async () => {
  const pageNo = tableApi.grid.getCurrentPage();
  const pageSize = tableApi.grid.getPageSize();

  const params: any = {
    pageNo,
    pageSize,
    ...tableApi.formApi.form.values,
  };
  const blob = await orderRefundExport(params);

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `退款对账_${Date.now()}.xlsx`;
  document.body.append(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);

  message.success('导出成功');
};
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="退款对账">
      <template #toolbar-tools>
        <a-button
          type="primary"
          @click="openExportModal"
          v-access:code="['sys:order:refund:export']"
        >
          导出
        </a-button>
      </template>
    </BasicTable>
  </Page>
</template>
